import axios from 'axios';
import mMapError from './error/aMapError';
import { message } from 'ant-design-vue';
import { Storage } from '@/util/storage';
//普通请求
export const httpRequest = (
  url,
  params,
  method,
  headers = 'application/x-www-form-urlencoded'
) => {
  return new Promise((resolve, reject) => {
    axios({
      method: method,
      url: url,
      params: method != 'post' ? params : '',
      data: method == 'post' ? params : '',
      headers: {
        token: Storage.get('token') ? Storage.get('token') : '',
        'conten-type': headers,
      },
      timeout: 30000,
    })
      .then((res) => {
        if (res.data?.status) {
          res.data.status == 200 ? resolve(res.data) : reject(res.data);
        } else {
          resolve(res.data);
        }
      })
      .catch((err) => {
        if (err.response) {
          let errMessage = err.response?.data?.message
            ? err?.response?.data?.message + err?.response?.data?.status
            : err?.response?.data?.error + err?.response?.data?.status;
          message.error(errMessage);
          err?.response?.data?.status == 401
            ? window.parent.postMessage(err.response.data, '*')
            : '';
          reject(err.response.data);
        } else {
          message.error(err.message);
          reject(err);
        }
      });
  });
};
//高德请求
export const aMapHttpRquest = (url, params, method = 'get') => {
  return new Promise((resolve, reject) => {
    axios({
      url: url,
      params:
        method != 'post'
          ? Object.assign(params, { key: process.env.VUE_APP_APIAK })
          : '',
      data: method == 'post' ? params : '',
      timeout: 10000,
    })
      .then((res) => {
        if (res.data.status == 1) {
          resolve(res.data);
        } else {
          //官方错误统一拦击解析
          message.error(mMapError[res.data.info] + res.data.infocode);
          reject(res.data);
        }
      })
      .catch((err) => {
        message.err(err);
        reject(err);
      });
  });
};
